package com.bocai.grainshop.member.service.impl;


import com.bocai.grainshop.member.dao.MemberLevelDao;
import com.bocai.grainshop.member.entity.MemberLevelEntity;
import com.bocai.grainshop.member.exception.EmailException;
import com.bocai.grainshop.member.exception.UsernameException;
import com.bocai.grainshop.member.vo.MemberUserLoginVo;
import com.bocai.grainshop.member.vo.MemberUserRegisterVo;
import com.bocai.grainshop.member.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.member.dao.MemberDao;
import com.bocai.grainshop.member.entity.MemberEntity;
import com.bocai.grainshop.member.service.MemberService;

import javax.annotation.Resource;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registMember(MemberUserRegisterVo registerVo) {
        MemberEntity entity = new MemberEntity();
        //查询默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getMemberLevelM();

        if (levelEntity!=null){

            entity.setLevelId(levelEntity.getId());
        }

        //自定义异常机制 发现异常往上抛
        boolEmailUnique(registerVo.getEmail());

        boolUsernameUnique(registerVo.getUserName());

        entity.setMobile(registerVo.getEmail());

        entity.setUsername(registerVo.getUserName());

        //密码需要加密处理 MD5盐值加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(registerVo.getPassword());
        entity.setPassword(encode);

        //设置其他默认信息

        this.save(entity);
    }

    @Override
    public void boolUsernameUnique(String username) throws UsernameException {
        int count = this.count(new QueryWrapper<MemberEntity>().eq("username", username));
        if(count>0){

            throw new UsernameException();
        }
    }

    @Override
    public void boolEmailUnique(String email) throws EmailException{
        int count = this.count(new QueryWrapper<MemberEntity>().eq("mobile", email));
        if(count == 0){

            throw new EmailException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginVo loginVo) {
        String ID = loginVo.getLoginacct();
        String password = loginVo.getPassword();
        MemberEntity username = this.getOne(new QueryWrapper<MemberEntity>().eq("username", ID));
        if(username!=null){
            String usernamePassword = username.getPassword();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(password, usernamePassword);
            if(matches){
                username.setNickname(loginVo.getLoginacct()+"憨憨！");
                return username;
            }else {
                return null;
            }
        }else {
            //登录失败
            return null;
        }
    }

    /**
     * @Author: SunJinbo
     * @Description  gitee登录
     * @Param [socialUser]
     * @return com.bocai.grainshop.member.entity.MemberEntity
     * @Data Created in 2022/4/14 16:09
     */
    @Override
    public MemberEntity GiteeLogin(SocialUser socialUser) {
        String userId = socialUser.getId();
        //判断用户是否使用此社交账号登录过
        MemberEntity user_id = this.getOne(new QueryWrapper<MemberEntity>().eq("user_id", userId));
        if(user_id!=null){
            //登录过 就更新口令和过期时间
            MemberEntity update = new MemberEntity();
            update.setId(user_id.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            update.setUsername(socialUser.getName());
            update.setNickname(socialUser.getName());
            this.updateById(update);
            //返回查询的用户信息
            user_id.setExpiresIn(socialUser.getExpires_in());
            user_id.setAccessToken(socialUser.getAccess_token());
            user_id.setNickname(socialUser.getName());
            user_id.setUsername(socialUser.getName());
            return user_id;
        }else {
            //就注册
            MemberEntity regist = new MemberEntity();
            regist.setEmail(socialUser.getEmail());
            regist.setNickname(socialUser.getName());
            regist.setCreateTime(new Date());
            regist.setUsername(socialUser.getName());
            regist.setLevelId(1l);
            regist.setAccessToken(socialUser.getAccess_token());
            regist.setExpiresIn(socialUser.getExpires_in());
            regist.setUserId(socialUser.getId());
            regist.setIntegration(3);
            this.save(regist);
            return regist;
        }
    }


}